package com.djf.word.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.djf.word.entity.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 订单Mapper接口
 * 
 * @author djf
 * @since 2025-01-08
 */
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
    
    /**
     * 根据用户ID查询订单列表
     * 
     * @param userId 用户ID
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE user_id = #{userId} AND deleted = 0 ORDER BY create_time DESC")
    List<Order> selectByUserId(@Param("userId") Long userId);
    
    /**
     * 根据订单状态查询订单列表
     * 
     * @param status 订单状态
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE status = #{status} AND deleted = 0 ORDER BY create_time DESC")
    List<Order> selectByStatus(@Param("status") String status);
    
    /**
     * 查询订单统计信息
     * 
     * @return 统计信息Map
     */
    @Select("SELECT " +
            "COUNT(*) as totalCount, " +
            "SUM(total_amount) as totalAmount, " +
            "AVG(total_amount) as avgAmount, " +
            "COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pendingCount, " +
            "COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) as completedCount, " +
            "COUNT(CASE WHEN status = 'CANCELLED' THEN 1 END) as cancelledCount " +
            "FROM order_202501 WHERE deleted = 0")
    Map<String, Object> selectOrderStatistics();
    
    /**
     * 根据金额范围查询订单
     * 
     * @param minAmount 最小金额
     * @param maxAmount 最大金额
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE total_amount BETWEEN #{minAmount} AND #{maxAmount} AND deleted = 0 ORDER BY total_amount DESC")
    List<Order> selectByAmountRange(@Param("minAmount") BigDecimal minAmount, @Param("maxAmount") BigDecimal maxAmount);
    
    /**
     * 根据产品名称模糊查询订单
     * 
     * @param productName 产品名称关键字
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE product_name LIKE CONCAT('%', #{productName}, '%') AND deleted = 0 ORDER BY create_time DESC")
    List<Order> selectByProductNameLike(@Param("productName") String productName);
    
    /**
     * 根据租户ID查询订单列表
     * 
     * @param tenantId 租户ID
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE tenant_id = #{tenantId} AND deleted = 0 ORDER BY create_time DESC")
    List<Order> selectByTenantId(@Param("tenantId") String tenantId);
    
    /**
     * 查询最近N天的订单
     * 
     * @param days 天数
     * @return 订单列表
     */
    @Select("SELECT * FROM order_202501 WHERE create_time >= DATE_SUB(NOW(), INTERVAL #{days} DAY) AND deleted = 0 ORDER BY create_time DESC")
    List<Order> selectRecentOrders(@Param("days") Integer days);
}